package test;

/**
 * 漏桶算法
 * <p>
 * Created by liuteng on 2018/10/10
 */
public class LeakyDemo {

    private long currentTime = System.currentTimeMillis();
    private int capatity = 1000;//桶容量
    private int count;//单位时间允许的次数
    private long water = capatity / 2;//初始化量，总容量的一半

    /**
     * 允许的次数
     *
     * @param count 次数
     */
    public LeakyDemo(int count) {
        if (count < 0) {
            count = 10;
        }
        this.count = count;
    }

    /**
     * 每次进入的水量
     *
     * @return 单次注入水量
     */
    private long getInPer() {
        return capatity / count;
    }

    public boolean isTooFast() {
        long now = System.currentTimeMillis();
        long out = now - currentTime;//应该流出的水量
        currentTime = now;
        System.out.println("应该流出的水量:" + out);
        water = Math.max(0, water - out);//当前水量
        System.out.println("当前水量:" + water);
        if ((water + getInPer()) < capatity) {
            water = water + getInPer();
            return false;
        } else {
            return true;
        }
    }

    public static void main(String[] args) throws InterruptedException {
        LeakyDemo leakyDemo = new LeakyDemo(20);
        for (int i = 0; i < 100; i++) {
            System.out.println(leakyDemo.isTooFast());
            Thread.sleep(20);
        }
    }
}
